from abc import ABC, abstractmethod


# 1. AIAssistant 抽象基类
class AIAssistant(ABC):
    def __init__(self, assistant_id, name, assistant_type, version, online, score):
        self._id = assistant_id
        self._name = name
        self._type = assistant_type
        self._version = version
        self._online = online
        self._score = score

    # 封装属性 - Getter和Setter
    @property
    def id(self):
        return self._id

    @id.setter
    def id(self, value):
        self._id = value

    @property
    def name(self):
        return self._name

    @name.setter
    def name(self, value):
        self._name = value

    @property
    def type(self):
        return self._type

    @type.setter
    def type(self, value):
        self._type = value

    @property
    def version(self):
        return self._version

    @version.setter
    def version(self, value):
        self._version = value

    @property
    def online(self):
        return self._online

    @online.setter
    def online(self, value):
        self._online = value

    @property
    def score(self):
        return self._score

    @score.setter
    def score(self, value):
        if 0 <= value <= 100:
            self._score = value
        else:
            print("❌ 能力评分必须在0-100之间")

    @abstractmethod
    def perform_task(self, task):
        pass

    def display_info(self):
        status = "🟢在线" if self._online else "🔴离线"
        print(f"ID: {self._id}, 名称: {self._name}, 类型: {self._type}, "
              f"版本: {self._version}, 状态: {status}, 能力评分: {self._score} [{self._type}]")


# 2. 具体助手子类
class TextAssistant(AIAssistant):
    def __init__(self, assistant_id, name, version, online, score, max_text_length=5000):
        super().__init__(assistant_id, name, "文本生成助手", version, online, score)
        self._max_text_length = max_text_length

    @property
    def max_text_length(self):
        return self._max_text_length

    @max_text_length.setter
    def max_text_length(self, value):
        self._max_text_length = value

    def perform_task(self, task):
        if self.online:
            print(f"✅ 【{self.name}】正在执行文本生成任务：{task}（最大长度：{self.max_text_length}字）")
        else:
            print(f"❌ {self.name} 当前离线，无法执行任务。")


class ImageAssistant(AIAssistant):
    def __init__(self, assistant_id, name, version, online, score, image_style="默认风格"):
        super().__init__(assistant_id, name, "图片生成助手", version, online, score)
        self._image_style = image_style

    @property
    def image_style(self):
        return self._image_style

    @image_style.setter
    def image_style(self, value):
        self._image_style = value

    def perform_task(self, task):
        if self.online:
            print(f"✅ 【{self.name}】正在生成图片：{task}（风格：{self.image_style}）")
        else:
            print(f"❌ {self.name} 当前离线，无法执行任务。")


class DataAnalysisAssistant(AIAssistant):
    def __init__(self, assistant_id, name, version, online, score, analysis_type="通用分析"):
        super().__init__(assistant_id, name, "数据分析助手", version, online, score)
        self._analysis_type = analysis_type

    @property
    def analysis_type(self):
        return self._analysis_type

    @analysis_type.setter
    def analysis_type(self, value):
        self._analysis_type = value

    def perform_task(self, task):
        if self.online:
            print(f"✅ 【{self.name}】正在分析数据：{task}（分析类型：{self.analysis_type}）")
        else:
            print(f"❌ {self.name} 当前离线，无法执行任务。")


class TranslationAssistant(AIAssistant):
    def __init__(self, assistant_id, name, version, online, score, languages="中英互译"):
        super().__init__(assistant_id, name, "翻译助手", version, online, score)
        self._languages = languages

    @property
    def languages(self):
        return self._languages

    @languages.setter
    def languages(self, value):
        self._languages = value

    def perform_task(self, task):
        if self.online:
            print(f"✅ 【{self.name}】正在翻译：{task}（支持语言：{self.languages}）")
        else:
            print(f"❌ {self.name} 当前离线，无法执行任务。")


class VoiceAssistant(AIAssistant):
    def __init__(self, assistant_id, name, version, online, score, voice_type="标准语音"):
        super().__init__(assistant_id, name, "语音助手", version, online, score)
        self._voice_type = voice_type

    @property
    def voice_type(self):
        return self._voice_type

    @voice_type.setter
    def voice_type(self, value):
        self._voice_type = value

    def perform_task(self, task):
        if self.online:
            print(f"✅ 【{self.name}】正在处理语音：{task}（语音类型：{self.voice_type}）")
        else:
            print(f"❌ {self.name} 当前离线，无法执行任务。")


# 3. AI管理器类
class AIManager:
    def __init__(self, max_size=100):
        self._assistants = []
        self._max_size = max_size
        self._initialize_sample_data()

    def _initialize_sample_data(self):
        """初始化示例数据"""
        sample_assistants = [
            VoiceAssistant("101", "小智", "v1.2", True, 85, "智能语音"),
            TextAssistant("102", "文小助", "v2.0", True, 92, 10000),
            ImageAssistant("103", "图灵", "v1.5", False, 88, "写实风格"),
            DataAnalysisAssistant("104", "数小析", "v1.0", True, 79, "统计分析"),
            TranslationAssistant("105", "翻译精灵", "v2.1", False, 95, "多语言翻译")
        ]
        self._assistants.extend(sample_assistants)

    def display_all_assistants(self):
        """显示所有助手列表"""
        print("所有AI助手列表：")
        for i, assistant in enumerate(self._assistants, 1):
            print(f"{i}. ", end="")
            assistant.display_info()

    def find_assistant_by_id(self, assistant_id):
        """根据ID查找助手"""
        for assistant in self._assistants:
            if assistant.id == assistant_id:
                return assistant
        return None

    def query_assistant_by_id(self):
        """根据ID查询助手详情"""
        assistant_id = input("请输入要查询的AI助手ID: ")
        assistant = self.find_assistant_by_id(assistant_id)
        if assistant:
            print("✅ 查询结果: ", end="")
            assistant.display_info()
        else:
            print(f"❌ 未找到ID为 {assistant_id} 的助手")

    def add_new_assistant(self):
        """添加新的AI助手"""
        if len(self._assistants) >= self._max_size:
            print("❌ 助手数量已达上限，无法添加")
            return

        print("添加新AI助手")
        assistant_id = input("请输入ID: ")

        # 检查ID是否已存在
        if self.find_assistant_by_id(assistant_id):
            print("❌ 该ID已存在")
            return

        name = input("请输入名称: ")
        print("请选择类型: 1-文本生成 2-图片生成 3-数据分析 4-翻译 5-语音")
        type_choice = input("请输入类型编号: ")

        type_map = {
            "1": "文本生成助手",
            "2": "图片生成助手",
            "3": "数据分析助手",
            "4": "翻译助手",
            "5": "语音助手"
        }

        assistant_type = type_map.get(type_choice, "文本生成助手")
        version = input("请输入版本号: ")
        online = input("是否在线？(1-是, 0-否): ") == "1"

        try:
            score = int(input("请输入能力评分(0-100): "))
        except ValueError:
            print("❌ 分数必须是数字")
            return

        # 根据类型创建助手对象
        if type_choice == "1":
            new_assistant = TextAssistant(assistant_id, name, version, online, score)
        elif type_choice == "2":
            new_assistant = ImageAssistant(assistant_id, name, version, online, score)
        elif type_choice == "3":
            new_assistant = DataAnalysisAssistant(assistant_id, name, version, online, score)
        elif type_choice == "4":
            new_assistant = TranslationAssistant(assistant_id, name, version, online, score)
        elif type_choice == "5":
            new_assistant = VoiceAssistant(assistant_id, name, version, online, score)
        else:
            new_assistant = TextAssistant(assistant_id, name, version, online, score)

        self._assistants.append(new_assistant)
        print(f"✅ 助手【{name}】添加成功！")

    def modify_assistant(self):
        """修改助手信息"""
        assistant_id = input("请输入要修改的AI助手ID: ")
        assistant = self.find_assistant_by_id(assistant_id)
        if not assistant:
            print("❌ 未找到该助手")
            return

        print("可修改属性列表为：name, type, version, online, score")
        user_input = input("请输入要修改的属性和值，用空格分割: ").split()
        if len(user_input) != 2:
            print("❌ 输入格式错误")
            return

        property_name, value = user_input

        if property_name == "name":
            assistant.name = value
        elif property_name == "type":
            assistant.type = value
        elif property_name == "version":
            assistant.version = value
        elif property_name == "online":
            assistant.online = value.lower() in ["1", "true", "是"]
        elif property_name == "score":
            try:
                assistant.score = int(value)
            except ValueError:
                print("❌ 分数必须是数字")
                return
        else:
            print("❌ 不支持修改该属性")
            return

        print(f"✅ 助手【{assistant_id}】修改成功！")

    def delete_assistant(self):
        """删除助手"""
        assistant_id = input("请输入要删除的AI助手ID: ")
        for i, assistant in enumerate(self._assistants):
            if assistant.id == assistant_id:
                name = assistant.name
                del self._assistants[i]
                print(f"✅ 助手【{name}】已删除。")
                return
        print(f"❌ 未找到ID为 {assistant_id} 的助手")

    def start_assistant(self):
        """启动助手服务"""
        assistant_id = input("请输入要启动的AI助手ID: ")
        assistant = self.find_assistant_by_id(assistant_id)
        if assistant:
            if assistant.online:
                print(f"助手【{assistant.name}】已在运行。")
            else:
                assistant.online = True
                print(f"✅ 助手【{assistant.name}】已启动。")
        else:
            print("❌ 未找到该助手")

    def stop_assistant(self):
        """停止助手服务"""
        assistant_id = input("请输入要停止的AI助手ID: ")
        assistant = self.find_assistant_by_id(assistant_id)
        if assistant:
            if not assistant.online:
                print(f"助手【{assistant.name}】已停止。")
            else:
                assistant.online = False
                print(f"✅ 助手【{assistant.name}】已停止。")
        else:
            print("❌ 未找到该助手")

    def assign_task(self):
        """分配任务"""
        assistant_id = input("请输入目标AI助手ID: ")
        assistant = self.find_assistant_by_id(assistant_id)
        if assistant:
            task = input("请输入任务内容: ")
            assistant.perform_task(task)
        else:
            print("❌ 未找到该助手")

    def show_statistics(self):
        """显示系统统计信息"""
        total_count = len(self._assistants)
        online_count = sum(1 for assistant in self._assistants if assistant.online)
        total_score = sum(assistant.score for assistant in self._assistants)
        avg_score = total_score / total_count if total_count > 0 else 0

        print("系统统计信息：")
        print(f"总助手数: {total_count}")
        print(f"在线助手数: {online_count}")
        print(f"离线助手数: {total_count - online_count}")
        print(f"平均能力评分: {avg_score:.2f}")

    def show_menu(self):
        """显示菜单"""
        print("\n" + "=" * 40 + " AI助手管理器 " + "=" * 40)
        print("1. 查看所有AI助手列表")
        print("2. 根据ID查询助手详情")
        print("3. 添加新的AI助手")
        print("4. 根据ID修改助手信息")
        print("5. 删除AI助手（按ID）")
        print("6. 启动AI助手服务")
        print("7. 停止AI助手服务")
        print("8. 为AI助手分配任务")
        print("9. 显示系统统计信息")
        print("0. 退出系统")
        print("=" * 93)

    def run(self):
        """运行管理器"""
        print("欢迎使用 AI助手管理器 v1.0")
        while True:
            self.show_menu()
            choice = input("请选择操作: ")

            if choice == "1":
                self.display_all_assistants()
            elif choice == "2":
                self.query_assistant_by_id()
            elif choice == "3":
                self.add_new_assistant()
            elif choice == "4":
                self.modify_assistant()
            elif choice == "5":
                self.delete_assistant()
            elif choice == "6":
                self.start_assistant()
            elif choice == "7":
                self.stop_assistant()
            elif choice == "8":
                self.assign_task()
            elif choice == "9":
                self.show_statistics()
            elif choice == "0":
                print("感谢使用AI助手管理器，再见！")
                break
            else:
                print("❌ 无效选择，请重新输入")


# 主程序入口
if __name__ == "__main__":
    manager = AIManager()
    manager.run()